#include <Windows.h>
#include "CommonHeader.h"

// Construct the test ui
CommonHeader::CommonHeader(QWidget* parent):
	QFrame(parent),
	m_bIsCanMove(false),
	m_bDisposed(false)
{
	Initialize();
}

// Destruct the test ui
CommonHeader::~CommonHeader()
{
	Destory();
}

// Init the UI
void CommonHeader::Initialize()
{
	setWindowFlags(Qt::FramelessWindowHint);
}

// Destory the UI
void CommonHeader::Destory()
{
	if (!GetDisposed())
	{
		SetDisposed(true);
	}
}

// Override event handler function to support resize frameless window
bool CommonHeader::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
#ifdef Q_OS_WIN
	MSG* msg = static_cast<MSG*>(message);

	if (msg->message == WM_NCHITTEST)
	{
		*result = HTTRANSPARENT;

		return true;
	}
#endif

	return QFrame::nativeEvent(eventType, message, result);
}

// Show the frame
void CommonHeader::showEvent(QShowEvent *ev)
{
	QFrame::showEvent(ev);
}

// Press the window
void CommonHeader::mousePressEvent(QMouseEvent *e)
{
	if (e->button() == Qt::LeftButton 
		&& !this->isMaximized() 
		&& !this->isFullScreen())
	{
		SetIsCanMove(true);

		m_LastClickPos = e->pos();
	}
}

// Move the window
void CommonHeader::mouseMoveEvent(QMouseEvent *e)
{
	if (GetIsCanMove()
		&& this->window() 
		&& !this->window()->isMaximized() 
		&& !this->window()->isFullScreen()) 
	{
		QPoint DifferPos = e->globalPos() - m_LastClickPos;

		this->window()->move(DifferPos);
	}

	QFrame::mouseMoveEvent(e);
}

void CommonHeader::mouseReleaseEvent(QMouseEvent *ev)
{
	SetIsCanMove(false);

	QFrame::mouseReleaseEvent(ev);
}
